<template>
  <div class="contentView" v-loading="loading" :style="`height:${contentHeight}px`">
    <div class="routeHeader">
      <el-button
        @click="submitForm('create')"
        type="primary"
        :disabled="loading"
        v-hasPermi="['outsource:outbound-task-order:save']"
        >保 存</el-button
      >
      <el-button
        @click="submitForm('submit')"
        type="primary"
        :disabled="loading"
        v-hasPermi="['outsource:outbound-task-order:submit']"
        >提 交</el-button
      >
      <el-button @click="goBack">关 闭</el-button>
    </div>
    <el-scrollbar :style="`height:${contentHeight - 63}px`">
      <el-form
        class="-mb-15px"
        :model="formData"
        :rules="formRules"
        ref="queryFormRef"
        :inline="true"
        label-width="130px"
      >
        <el-form-item label="订单号" prop="orderNumber">
          <el-input disabled v-model="formData.orderNumber" placeholder="订单号" />
        </el-form-item>
        <el-form-item label="订单日期" prop="orderDate">
          <el-date-picker
            v-model="selectedDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择订单日期"
          />
        </el-form-item>
        <el-form-item label="供应商名称" prop="supplierName">
          <el-input
            v-model="formData.supplierName"
            placeholder="供应商名称"
            readonly
            class="!w-220px"
          >
            <template #append>
              <el-button @click="supplierSelect" :icon="Search" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="业务员" prop="salesName">
          <el-input disabled v-model="formData.salesName" placeholder="业务员" />
        </el-form-item>
        <el-form-item label="税率" prop="itaxrate">
          <el-input disabled v-model="formData.itaxrate" placeholder="税率" />
        </el-form-item>
        <el-form-item label="部门" prop="affiliatedFunction">
          <el-input disabled v-model="formData.affiliatedFunction" placeholder="部门" />
        </el-form-item>
        <el-form-item label="收付款协议编码" prop="cvenpuomprotocol">
          <el-input disabled v-model="formData.cvenpuomprotocol" placeholder="收付款协议编码" />
        </el-form-item>
        <el-form-item label="收付款协议名称" prop="protocolName">
          <el-input disabled v-model="formData.protocolName" placeholder="收付款协议名称" />
        </el-form-item>
        <el-form-item label="计划到货日期" prop="planArriveTime">
          <el-date-picker
            v-model="formData.planArriveTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="计划到货日期"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" placeholder="备注" />
        </el-form-item>
      </el-form>
      <div>
        <div class="mt-10px mb-10px"
          ><el-button type="primary" @click="quoteSelect">引用外协任务</el-button></div
        >
        <el-table v-loading="loading" :data="list" border>
          <el-table-column label="序号" align="center" type="index" fixed="left" width="80" />
          <el-table-column
            label="委外方式"
            align="left"
            prop="dictOutsourceMode"
            width="180"
            header-align="center"
          >
            <template #default="scope">
              <el-select
                v-model="scope.row.dictOutsourceMode"
                placeholder="请选择委外方式"
                clearable
                class="!w-150px"
              >
                <el-option
                  v-for="(dict, index) in getIntDictOptions(DICT_TYPE.DICT_OUTSOURCE_MODE)"
                  :key="index"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            label="产品编号"
            align="left"
            prop="productNumber"
            width="120"
            header-align="center"
          />
          <el-table-column
            label="部件编号"
            align="left"
            prop="partNumber"
            width="120"
            header-align="center"
          />
          <el-table-column
            label="部件名称"
            align="left"
            prop="partName"
            width="120"
            header-align="center"
          />
          <el-table-column
            label="图纸图号"
            align="left"
            prop="drawingNumber"
            width="120"
            header-align="center"
          >
            <template #default="scope">
              <el-button type="primary" link @click="jumpPdfFile(scope.row.drawingNumber)">{{
                scope.row.drawingNumber
              }}</el-button>
            </template>
          </el-table-column>
          <el-table-column
            label="部件规格"
            align="left"
            prop="partSpecification"
            width="120"
            header-align="center"
          />
          <el-table-column
            label="材质"
            align="left"
            prop="material"
            width="120"
            header-align="center"
          />
          <el-table-column
            label="规格"
            align="left"
            prop="specification"
            width="120"
            header-align="center"
          />
          <el-table-column
            label="净尺寸  (长)"
            align="left"
            prop="netSizeLength"
            width="120"
            header-align="center"
          />
          <el-table-column
            label="净尺寸  (宽)"
            align="left"
            prop="netSizeWidth"
            width="120"
            header-align="center"
          />
          <el-table-column
            label="下料尺寸(长)"
            align="left"
            prop="cuttingSizeLength"
            width="120"
            header-align="center"
          />
          <el-table-column
            label="下料尺寸(宽)"
            align="left"
            prop="cuttingSizeWidth"
            width="120"
            header-align="center"
          />
          <el-table-column
            label="计划数量"
            align="left"
            prop="planQuantity"
            width="120"
            header-align="center"
          />
          <el-table-column
            label="下单数量"
            align="left"
            prop="purchaseQuantity"
            width="180"
            header-align="center"
          >
            <template #default="scope">
              <el-input-number
                v-nextInput="'purchaseQuantity'"
                name="purchaseQuantity"
                controls-position="right"
                :step="1"
                :min="0"
                v-model="scope.row.purchaseQuantity"
                class="!w-150px"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="单位"
            align="left"
            prop="partUnit"
            width="120"
            header-align="center"
          />
          <el-table-column
            label="税率(%)"
            align="left"
            prop="itaxrate"
            width="120"
            header-align="center"
          />
          <el-table-column
            label="含税单价"
            align="left"
            prop="taxIncludedPrice"
            width="180"
            header-align="center"
          >
            <template #default="scope">
              <el-input-number
                v-nextInput="'taxIncludedPrice'"
                name="taxIncludedPrice"
                controls-position="right"
                :precision="2"
                :step="0.1"
                :min="0"
                @change="taxChange(scope.row)"
                v-model="scope.row.taxIncludedPrice"
                class="!w-150px"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="含税金额"
            align="left"
            prop="priceTaxTotal"
            width="180"
            header-align="center"
          >
            <template #default="scope">
              <el-input-number
                v-nextInput="'priceTaxTotal'"
                name="priceTaxTotal"
                controls-position="right"
                :precision="2"
                :step="0.1"
                :min="0"
                v-model="scope.row.priceTaxTotal"
                class="!w-150px"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="金额"
            align="left"
            prop="priceExcludingTax"
            width="180"
            header-align="center"
          >
            <template #default="scope">
              <el-input-number
                v-nextInput="'priceExcludingTax'"
                name="priceExcludingTax"
                controls-position="right"
                :precision="2"
                :step="0.1"
                :min="0"
                v-model="scope.row.priceExcludingTax"
                class="!w-150px"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="税额"
            align="left"
            prop="taxRelief"
            width="180"
            header-align="center"
          >
            <template #default="scope">
              <el-input-number
                v-nextInput="'taxRelief'"
                name="taxRelief"
                controls-position="right"
                :precision="2"
                :step="0.1"
                :min="0"
                v-model="scope.row.taxRelief"
                class="!w-150px"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="单价"
            align="left"
            prop="unitPrice"
            width="180"
            header-align="center"
          >
            <template #default="scope">
              <el-input-number
                v-nextInput="'unitPrice'"
                name="unitPrice"
                controls-position="right"
                :precision="2"
                :step="0.1"
                :min="0"
                v-model="scope.row.unitPrice"
                class="!w-150px"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="备注"
            align="left"
            prop="remark"
            width="200"
            header-align="center"
          >
          <template #default="scope">
          <el-input
            v-model="scope.row.remark"
            class="!w-160px"
          />
        </template>
        </el-table-column>
          <el-table-column
            label="需求交期"
            align="left"
            prop="requirementTime"
            width="180"
            header-align="center"
          >
            <template #default="scope">
              <el-date-picker
                v-model="scope.row.requirementTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="选择订单日期"
                class="!w-150px"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="申购单号"
            align="left"
            prop="requisitionForm"
            width="120"
            header-align="center"
          />
          <el-table-column label="操作" align="center" width="80" fixed="right">
            <template #default="scope">
              <el-button link type="danger" @click="handleDelete(scope.$index)">移除行</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-scrollbar>
    <!-- 供应商 -->
    <OutboundSupplierForm ref="supplierRef" @success="supplierReftData" />
    <!-- 引用外协任务 -->
    <OutboundQuoteForm ref="quoteRef" @success="quoteData" />
  </div>
</template>
<script setup lang="ts">
import { jumpPdfFile } from '@/utils/formCreate'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { useTagsViewStore } from '@/store/modules/tagsView'
import * as OutboundTaskOrderApi from '@/api/outsource/outsourceIndentManage/outboundTaskOrder'
import OutboundSupplierForm from './OutboundSupplierForm.vue'
import OutboundQuoteForm from './OutboundQuoteForm.vue'
import { Search } from '@element-plus/icons-vue'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const loading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const list = ref<any[]>([])
const formData = ref({
  orderNumber: undefined,
  orderDate: undefined,
  supplierName: undefined,
  salesName: undefined,
  itaxrate: undefined,
  affiliatedFunction: undefined,
  cvenpuomprotocol: undefined,
  protocolName: undefined,
  planArriveTime: undefined,
  remark: undefined
})
const formRules = reactive({
  orderDate: [{ required: true, message: '订单日期不能为空', trigger: 'change' }],
  supplierName: [{ required: true, message: '供应商名称不能为空', trigger: 'change' }],
  salesName: [{ required: true, message: '业务员不能为空', trigger: 'change' }],
  itaxrate: [{ required: true, message: '税率不能为空', trigger: 'change' }],
  affiliatedFunction: [{ required: true, message: '部门不能为空', trigger: 'change' }],
  cvenpuomprotocol: [{ required: true, message: '收付款协议编码不能为空', trigger: 'change' }],
  protocolName: [{ required: true, message: '收付款协议名称不能为空', trigger: 'change' }]
})
const queryFormRef = ref() // 表单 Ref
const { query } = useRoute() // 路由的查询
const selectedDate = ref<any>('')
const now = new Date()
const formattedNow = `${now.getFullYear()}-${('0' + (now.getMonth() + 1)).slice(-2)}-${(
  '0' + now.getDate()
).slice(-2)}`
selectedDate.value = formattedNow as any
/** 打开弹窗 */
const getList = async () => {
  let ids = JSON.parse((query as any).ids)
  loading.value = true
  resetForm()
  try {
    const data = await OutboundTaskOrderApi.getOutboundTaskOrderList(ids)
    list.value = data
  } finally {
    loading.value = false
  }
}

/** 提交表单 */
const submitForm = async (val) => {
  formData.value.orderDate = selectedDate.value
  // 校验表单
  if (!queryFormRef) return
  const valid = await queryFormRef.value.validate()
  if (!valid) return
  list.value.map((item) => {
    if (!item.purchaseQuantity) {
       message.error('下单数量不能为空')
       return false
    }
    if (!item.taxIncludedPrice) {
       message.error('含税单价不能为空')
       return false
    }
    if (!item.priceTaxTotal) {
       message.error('含税金额不能为空')
       return false
    }
    if (!item.priceExcludingTax) {
       message.error('金额不能为空')
       return false
    }
    if (!item.taxRelief) {
       message.error('税额不能为空')
       return false
    }
    if (!item.unitPrice) {
       message.error('单价不能为空')
       return false
    }
  })
  list.value.map((item) => {
    item.orderNumber = formData.value.orderNumber
    item.orderDate = formData.value.orderDate
    item.supplierName = formData.value.supplierName
    item.salesName = formData.value.salesName
    item.affiliatedFunction = formData.value.affiliatedFunction
    item.cvenpuomprotocol = formData.value.cvenpuomprotocol
    item.protocolName = formData.value.protocolName
    item.planArriveTime = formData.value.planArriveTime
    item.remark = formData.value.remark
    item.taskOrderId = item.id
  })

  // 提交请求
  loading.value = true
  try {
    // const data = list.value as unknown as OutboundTaskOrderApi.OutboundTaskOrderVO
    const data = {
      createList: list.value
    }
    if (val === 'create') {
      await OutboundTaskOrderApi.createOutboundTaskOrder(data)
      message.success(t('common.createSuccess'))
      goBack()
    } else {
      await OutboundTaskOrderApi.submitOutboundTaskOrder(data)
      message.success(t('common.updateSuccess'))
      goBack()
    }
  } finally {
    loading.value = false
  }
}

/** 含税计算 */
const taxChange = (data) => {
  if (!data.itaxrate) {
    return message.notifyError('无税率,请选择供应商')
  }
  data.priceTaxTotal = data.purchaseQuantity * data.taxIncludedPrice // 含税金额
  data.priceExcludingTax =
    data.taxIncludedPrice * ((100 - data.itaxrate) / 100) * data.purchaseQuantity // 金额
  data.taxRelief = data.priceTaxTotal - data.priceExcludingTax // 税额
  data.unitPrice = data.taxIncludedPrice * ((100 - data.itaxrate) / 100) // 单价
}

/** 供应商显示 */
const supplierRef = ref()
const deptId = ref()
const supplierSelect = () => {
  supplierRef.value.open(deptId.value)
}

/** 供应商数据 */
const supplierReftData = (data) => {
  deptId.value = data.deptId
  supplierData(data.deptId)
}

/** 供应商带出数据 */
const supplierData = async (id: number) => {
  try {
    const data = await OutboundTaskOrderApi.getOutboundTaskOrderSrmInvoice(id)
    formData.value = data
    formData.value.itaxrate = data.invoiceTaxRateName
    const itaxrate = parseFloat(data.invoiceTaxRateName)
    list.value.map((item) => {
      item.itaxrate = itaxrate
    })
  } finally {
  }
}

/** 引用显示 */
const quoteRef = ref()
const quoteSelect = () => {
  const ids = list.value.map((item) => {
    return (item as any).id
  })
  quoteRef.value.open(ids)
}

/** 引用数据 */
const quoteData = (data) => {
  list.value = data
}

/** 移除行 */
const handleDelete = async (index) => {
  list.value.splice(index, 1)
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    orderNumber: undefined,
    orderDate: undefined,
    supplierName: undefined,
    salesName: undefined,
    itaxrate: undefined,
    affiliatedFunction: undefined,
    cvenpuomprotocol: undefined,
    protocolName: undefined,
    planArriveTime: undefined,
    remark: undefined
  }
  queryFormRef.value?.resetFields()
}

/** 关闭 */
const tagsViewStore = useTagsViewStore()
const route = useRouter() // 路由
const goBack = async () => {
  //获取当前路由并删除tagView
  tagsViewStore.delView(route.currentRoute.value)
  //跳转列表页
  route.push({
    path: '/outsource/outsource/indentManage/outboundTaskOrder'
  })
}

/** 初始化 **/
const contentHeight = ref(0)
onMounted(async () => {
  contentHeight.value = document.body.clientHeight - 127
  getList()
})
</script>
